package com.xmy.cultivate.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xmy.cultivate.entity.*;
import com.xmy.cultivate.service.*;
import com.xmy.cultivate.util.Code;
import com.xmy.cultivate.util.ConfigData;
import com.xmy.cultivate.util.PageResult;
import com.xmy.cultivate.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author min
 * @since 2022-12-27
 */
@RestController
@RequestMapping("/api/trackDetail")
public class TrackDetailController extends BaseController{
    @Autowired
    ITrackService iTrackService;

    @Autowired
    ITrackDetailService iTrackDetailService;

    @Autowired
    IStaffService iStaffService;

    @Autowired
    IOrganizationService iOrganizationService;

    @Autowired
    ISubjectsService iSubjectsService;

    @Autowired
    ICourseTypeService iCourseTypeService;

    @Autowired
    IMqPushService iMqPushService;

    @Autowired
    IGradeService iGradeService;


    @GetMapping()
    public Result findAll(@RequestParam Map<String,String> reMap){

        Integer pageNum = StringUtils.isEmpty(reMap.get("pageNum")) ? 1 : Integer.valueOf(reMap.get("pageNum"));
        Integer pageSize = StringUtils.isEmpty(reMap.get("pageSize")) ? 10: Integer.valueOf(reMap.get("pageSize"));
        IPage<TrackDetail> iPage = new Page<>(pageNum,pageSize);

        String trackId = reMap.get("trackId");

        String name = reMap.get("name");

        Track track = iTrackService.getById(trackId);


        QueryWrapper<TrackDetail> queryWrapper =  new QueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotBlank(trackId),"track_id",trackId);
        if(StringUtils.isNotBlank(name)){
            if(track.getType().equals(2)){
                queryWrapper.inSql("sourse_id","select id from organization where name like '%"+name+"%'");
            }else {
                queryWrapper.inSql("sourse_id","select id from staff where name like '%"+name+"%'");
            }
        }



        iTrackDetailService.findAll(iPage,queryWrapper);
        return new Result(Code.OK,new PageResult(iPage.getRecords(),iPage.getTotal(),iPage.getPages()));
    }


    @GetMapping(value = "/{id}",name = "course:findbyid")
    public Result findById(@PathVariable(value = "id") Long id){
        //System.out.print("findById");
        Track track = iTrackService.getById(id);
        return new Result(Code.OK,track);
    }

    @PostMapping()
    public Result save(@RequestBody Track track){
        iTrackService.save(track);
        //iMqPushService.updateTrackDetail();
        //System.out.println(course);
        return new Result(Code.OK);
    }

    @PutMapping("/{id}")
    public Result update(@PathVariable(value = "id") String id,@RequestBody Track track){

        iTrackService.updateById(track);
        return new Result(Code.OK);
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable(value = "id") Long id){
        boolean rs =  iTrackService.removeById(id);
        return new Result(rs?Code.OK:Code.ERROR);
    }

    //市场部
    @GetMapping("list")
    public Result list(@RequestParam Map<String,String> reMap){

        int pageNum = reMap.get("pageNum") != null && !reMap.get("pageNum").isEmpty() ? Integer.parseInt(reMap.get("pageNum")) : 1;
        int pageSize = reMap.get("pageSize") != null && !reMap.get("pageSize").isEmpty() ? Integer.parseInt(reMap.get("pageSize")) : 10;

        IPage<TrackDetail> iPage = new Page<>(pageNum,pageSize);

        String trackId = reMap.get("trackId");

        String name = reMap.get("name");

        String schoolIdStr = reMap.get("schoolId");
        String yearClassIdStr = reMap.get("yearClassId");
        String classTypeIdStr = reMap.get("classTypeId");
        String subjectsIdStr = reMap.get("subjectsId");

        QueryWrapper<TrackDetail> queryWrapper =  new QueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotBlank(trackId),"track_id",trackId);
        queryWrapper.like(StringUtils.isNotBlank(schoolIdStr),"school_id_str",schoolIdStr);
        queryWrapper.like(StringUtils.isNotBlank(yearClassIdStr),"year_class_id_str",yearClassIdStr);
        queryWrapper.like(StringUtils.isNotBlank(classTypeIdStr),"class_type_id_str",classTypeIdStr);
        queryWrapper.like(StringUtils.isNotBlank(subjectsIdStr),"subjects_id_str",subjectsIdStr);
        if(StringUtils.isNotBlank(name)){
            queryWrapper.inSql("sourse_id","select id from staff where name like '%"+name+"%'");
        }

        iTrackDetailService.page(iPage,queryWrapper);
        for (TrackDetail trackDetail: iPage.getRecords()) {
            //教师名称
            Staff staff = iStaffService.getById(trackDetail.getSourseId());
            if(staff !=null){
                trackDetail.setName(staff.getName());
            }
            //校区名称
            if (trackDetail.getSchoolIdStr() != null && !trackDetail.getSchoolIdStr().isEmpty()) {
                List<Organization> organizationList = iOrganizationService.list(new QueryWrapper<Organization>().inSql("id", trackDetail.getSchoolIdStr()));
                if (!organizationList.isEmpty()) {
                    StringBuilder organizationStr = new StringBuilder();
                    for (Organization organization : organizationList) {
                        if (organizationStr.length() > 0) {
                            organizationStr.append(",");
                        }
                        organizationStr.append(organization.getName());
                    }
                    trackDetail.setSchoolIdStr(organizationStr.toString());
                }
            }
            //科目名称
            if (trackDetail.getSubjectsIdStr() != null && !trackDetail.getSubjectsIdStr().isEmpty()) {
                List<Subjects> subjectsList = iSubjectsService.list(new QueryWrapper<Subjects>().inSql("id", trackDetail.getSubjectsIdStr()));
                if (!subjectsList.isEmpty()) {
                    StringBuilder subjectsIdStrBuilder = new StringBuilder();
                    for (Subjects subjects : subjectsList) {
                        if (subjectsIdStrBuilder.length() > 0) {
                            subjectsIdStrBuilder.append(",");
                        }
                        subjectsIdStrBuilder.append(subjects.getName());
                    }
                    trackDetail.setSubjectsIdStr(subjectsIdStrBuilder.toString());
                }
            }
            //年级
            if (trackDetail.getYearClassIdStr() != null && !trackDetail.getYearClassIdStr().isEmpty()) {
                String[] strings = trackDetail.getYearClassIdStr().split(",");
                StringBuilder yearClassIdStrBuilder = new StringBuilder();
                for (String string : strings) {
                    String yearClassForNum = ConfigData.getYearClassForNum(Integer.valueOf(string));
                    if (yearClassIdStrBuilder.length() > 0) {
                        yearClassIdStrBuilder.append(",");
                    }
                    yearClassIdStrBuilder.append(yearClassForNum);
                }
                trackDetail.setYearClassIdStr(yearClassIdStrBuilder.toString());
            }
            //班型
            if (trackDetail.getClassTypeIdStr() != null && !trackDetail.getClassTypeIdStr().isEmpty()) {
                List<CourseType> courseTypeList = iCourseTypeService.list(new QueryWrapper<CourseType>().inSql("id", trackDetail.getClassTypeIdStr()));
                if (!courseTypeList.isEmpty()) {
                    StringBuilder classTypeIdStrBuilder = new StringBuilder();
                    for (CourseType courseType : courseTypeList) {
                        if (classTypeIdStrBuilder.length() > 0) {
                            classTypeIdStrBuilder.append(",");
                        }
                        classTypeIdStrBuilder.append(courseType.getName());
                    }
                    trackDetail.setClassTypeIdStr(classTypeIdStrBuilder.toString());
                }
            }

            if (trackDetail.getGradeIdStr() != null && !trackDetail.getGradeIdStr().isEmpty()) {
                List<Grade> gradeList = iGradeService.list(new QueryWrapper<Grade>().inSql("id", trackDetail.getGradeIdStr()));
                if (!gradeList.isEmpty()) {
                    StringBuilder gradeIdStrBuilder = new StringBuilder();
                    for (Grade grade : gradeList) {
                        if (gradeIdStrBuilder.length() > 0) {
                            gradeIdStrBuilder.append(",");
                        }
                        gradeIdStrBuilder.append(grade.getName());
                    }
                    trackDetail.setGradeIdStr(gradeIdStrBuilder.toString());
                }
            }



        }
        return new Result(Code.OK,new PageResult<>(iPage.getRecords(),iPage.getTotal(),iPage.getPages()));
    }

}
